
import bpy
import bmesh

from bpy_extras.io_utils import unpack_list





def f_构建bl网格(me, mesh): #, verts_loc, tot_loops
	#清除网格
	bm = bmesh.new()
	bm.to_mesh(me)
	bm.free()
	

	#print('***f_构建bl网格 = ', len(mesh))

	顶点 = mesh[0]
	法线 = mesh[1]
	UV1 = mesh[2]
	UV2 = mesh[3]

	UV = mesh[4]

	面法线 = mesh[5]
	面中心 = mesh[6]
	边索引 = mesh[7]
	面索引 = mesh[8]
	材质ID = mesh[9]
	材质槽 = mesh[10]


	me.vertices.add(len(顶点))
	me.vertices.foreach_set("co", unpack_list(顶点))

	me.edges.add(len(边索引))
	me.edges.foreach_set("key", unpack_list(边索引))
	
	

	面r = len(面索引)
	if 面r <= 0 : return

	loops_vert_idx = 面索引[0]
	faces_loop_start = 面索引[1]
	faces_loop_total = 面索引[2]

	
	
	#print('材质槽 = ', 材质槽, 材质ID, len(faces_loop_start))
	槽数量 = len(材质槽)
	for i, mat in enumerate(材质槽):
		if len(me.materials) < 槽数量:
			me.materials.append(mat)
		else:
			me.materials[i] = mat

	me.loops.add(len(loops_vert_idx))
	me.loops.foreach_set("vertex_index", loops_vert_idx)
	

	me.polygons.add(len(faces_loop_start))
	me.polygons.foreach_set("loop_start", faces_loop_start)
	me.polygons.foreach_set("loop_total", faces_loop_total)
	me.polygons.foreach_set("material_index", 材质ID)

	#print("uv = ", UV)
	for i, e in enumerate(UV):
		index = me.uv_layers.find('UV'+str(i))
		if index >= 0 :
			uvmap = me.uv_layers[index]
		else:
			uvmap = me.uv_layers.new(name='UV'+str(i))
		uvmap.data.foreach_set("uv", unpack_list(e))

	
	#for mat in me.materials:
	'''if len(me.uv_layers) <= 0:
		me.uv_layers.new(name='UV1')
	UV = me.uv_layers[0]
	UV.data.foreach_set("uv", unpack_list(UV1))'''
	

	me.update()
	me.validate()


def f_填充bl网格顶点(me, verts_loc):
	me.vertices.add(len(verts_loc))
	me.vertices.foreach_set("co", unpack_list(verts_loc))

	me.update()
	me.validate()
	






	



